#include "../Misc/part2-3_shared.h"

int main(int argc, char **argv) {
	
	DEHT *deht;
	char user_input[MAX_INTPUT_SIZE];
	unsigned char deht_key[MAX_HASH_SIZE];
	int deht_key_length;
	char password[MAX_PASSWORD_LENGTH];
	int status;
	int finish = 0;
	char c;

	if (argc != 2) {
		fprintf(stderr, "Error: Usage exhaustive_query <filenames prefix>\n");
		exit(1);
	}

	deht = load_DEHT_from_files(argv[1], cryptHashToTable, cryptHashTo64bit);
	if (deht == NULL)
	{
		exit(1);
	}

	if (!strcmp((deht->header.sHashName),"MD5")) {
		deht_key_length = MD5_OUTPUT_LENGTH_IN_BYTES;
	}
	else {
		deht_key_length = SHA1_OUTPUT_LENGTH_IN_BYTES;
	}

	if (deht == NULL) {
		exit(1);
	}

	while (!finish) {
		printf(">>");

		/* read hashed password from user */
		fgets(user_input,MAX_INTPUT_SIZE,stdin);
		if (user_input[strlen(user_input) - 1] != '\n') {
			fprintf(stderr,"Input to long, please try again...\n");
			while ( (c = getchar()) != '\n');
			continue;
		}
		if (user_input[0] == '\n'){
			continue;
		}
		user_input[strlen(user_input) - 1] = '\0';

		if (!strcmp(user_input, "quit")) {
			finish = 1;
			continue;
		}

		/* convert password to binary data */
		status = hexa2binary(user_input, deht_key, MAX_HASH_SIZE);
		if (status == -1) {
			fprintf(stderr,"Non hexa\n");
			continue;
		}

		if (strlen(user_input) != deht_key_length * 2) {
			fprintf(stderr,"hash does not fit the supported hash function\n");
			continue;
		}

		status = query_DEHT(deht, deht_key, deht_key_length, (unsigned char*)password, MAX_PASSWORD_LENGTH);
		if (status == DEHT_STATUS_FAIL) {
			lock_DEHT_files(deht);
			exit(1);
		}
		if (status == DEHT_STATUS_NOT_NEEDED) {
			printf("Sorry but this hash doesn't appears in pre-processing\n");
		}
		else {
			password[status]='\0';
			printf("Try to login with password \"%s\"\n", password);
		}
	}

	return 0;
}
